<!--
/**
* @description 一厂一策规则
* @author wind-lc
* @date 2020-05-28
*/
-->
<template>
  <div class="one-factory-one-policy">
    <form-loading :formLoadingVisible="!pageReady"></form-loading>
    <!-- 数据源 -->
    <div class="one-factory-one-policy-source">
      <a-form-model :model="searchForm"
                    ref="searchForm"
                    class="custom-form-item-bottom"
                    labelAlign="left"
                    :label-col="labelCol"
                    :wrapper-col="wrapperCol">
        <a-form-model-item label="数据源"
                           prop="source">
          <a-select v-model="searchForm.source"
                    placeholder="请选择数据源"
                    @change="getTreeData">
            <a-select-option v-for="(item,index) in sourcelList"
                             :key="index"
                             :value="item.value">{{item.name}}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label=""
                           prop="name"
                           :label-col="{span: 0}"
                           :wrapper-col="{span: 24}">
          <a-input-search v-model="searchForm.name"
                          placeholder="请输入企业名称"
                          @keyup.enter="getTreeData"
                          @search="getTreeData" />
        </a-form-model-item>
      </a-form-model>
      <a-tree v-model="checkedKeys"
              :showLine="true"
              :showIcon="true"
              :tree-data="treeData"
              @select="treeSelect"
              class="one-factory-one-policy-tree">
        <template slot="custom-folder" slot-scope="{ expanded }">
          <a-icon :type="expanded ? 'folder-open' : 'folder'" theme="filled"/>
        </template>
      </a-tree>
    </div>
    <!-- 数据源 -->
    <!-- 规则设置 -->
    <div class="one-factory-one-policy-rule-table">
      <a-button type="primary"
                @click="saveRule"
                :loading="saveLoading"
                :disabled="saveDisabled">批量设置</a-button>
      <a-tabs :defaultActiveKey="0">
        <a-tab-pane v-for="(item,index) in ruleData"
                    :tab="item.name"
                    :key="index"
                    class="tabs-content">
          <a-table rowKey="equipmentIds"
                   :columns="columns"
                   :dataSource="item.data"
                   bordered
                   :rowSelection="rowSelection(item)"
                   :loading="item.loading"
                   :pagination="item.pagination"
                   @change="tableChange($event,item)">
          </a-table>
        </a-tab-pane>
      </a-tabs>
    </div>
    <!-- 规则设置 -->
  </div>
</template>
<script>
import { FormModel, Select, Input, Tree, Button, Tabs, Table, Icon } from 'ant-design-vue'
import { getDictData } from '@/request/api/common'
import { getHnEntinfoAndWorkshop, queryAllRuleEquipment, queryChooseEquipmentId, saveRule } from '@/request/api/ruleConfig/oneFactoryOnePolicy'
import { getCustomIconTreeData } from '@/utils/index'
export default {
  name: 'oneFactoryOnePolicy',
  components: {
    AFormModel: FormModel,
    AFormModelItem: FormModel.Item,
    ASelect: Select,
    ASelectOption: Select.Option,
    AInputSearch: Input.Search,
    ATree: Tree,
    AButton: Button,
    ATabs: Tabs,
    ATabPane: Tabs.TabPane,
    ATable: Table,
    AIcon: Icon
  },
  data () {
    return {
      // 页面完成
      pageReady: false,
      // 数据字典
      dataDictionary: {},
      // 顶部搜索表单
      searchForm: {},
      // 表单布局
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      // 数据源列表
      sourcelList: [],
      // 企业树
      treeData: [],
      // 选中的企业及生产线
      checkedKeys: [],
      // 预警表头
      columns: [
        {
          title: '序号',
          align: 'center',
          ellipsis: true,
          width: 80,
          customRender: (text, record, index) => {
            return index + 1
          }
        },
        {
          title: '设备名称',
          align: 'center',
          ellipsis: true,
          dataIndex: 'equipmentName'
        },
        {
          title: '设备ID',
          align: 'center',
          ellipsis: true,
          dataIndex: 'equipmentId'
        },
        {
          title: '污染分型',
          align: 'center',
          ellipsis: true,
          dataIndex: 'polluteType',
          customRender: (text, record, index) => {
            let txt = ''
            this.dataDictionary['Y-0B-008'].forEach(el => {
              if (text === el.value) {
                txt = el.name
              }
            })
            return txt
          }
        },
        {
          title: '设备状态',
          align: 'center',
          ellipsis: true,
          dataIndex: 'equipmentType',
          customRender: (text, record, index) => {
            let txt = ''
            this.dataDictionary['Y-002'].forEach(el => {
              if (text === el.value) {
                txt = el.name
              }
            })
            return txt
          }
        }
      ],
      // 规则数据
      ruleData: [],
      // 企业选中信息
      equipmentInfo: {},
      // 设置loading
      saveLoading: false,
      // 设置禁用
      saveDisabled: true
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    // 初始化
    async init () {
      // 获取数据字典
      this.dataDictionary = await this.getDataDictionary()
      // 数据源类型
      this.sourcelList = this.dataDictionary['Y-0B-009']
      this.searchForm.source = '3'
      // 获取企业树
      this.getTreeData()
    },
    // 获取数据字典
    getDataDictionary () {
      return new Promise((resolve, reject) => {
        getDictData('Y-0B-009,W-063,Y-002,Y-0B-008').then(res => {
          resolve(res.data)
        }).catch(error => {
          reject(error)
          console.log(error)
        })
      })
    },
    // 获取企业树
    getTreeData () {
      this.pageReady = false
      getHnEntinfoAndWorkshop({
        sources: this.searchForm.source,
        name: this.searchForm.name,
        ruleType: '1'
      }).then(res => {
        if (res.code === '0') {
          this.treeData = getCustomIconTreeData(res.data)
        }
        this.pageReady = true
      }).catch(error => {
        console.log(error)
        this.pageReady = true
      })
    },
    // 获取设备数据
    getEquipmentData (entinfoId, workshopId = '') {
      // 记住选中信息
      this.equipmentInfo = {
        entinfoId: entinfoId,
        workshopId: workshopId
      }
      this.pageReady = false
      // 获取生产线或者企业设备
      queryAllRuleEquipment({
        pageNum: 1,
        pageSize: 10,
        param: {
          entinfoId: this.equipmentInfo.entinfoId,
          workshopId: this.equipmentInfo.workshopId
        }
      }).then(res => {
        if (res.code === '0') {
          // 创建树结构
          this.ruleData = this.dataDictionary['W-063'].map(el => {
            return {
              id: el.id,
              value: el.value,
              name: el.name,
              loading: false,
              pagination: {
                current: res.data.pageNum, // 当前页数
                pageSize: 10, // 每页显示数量
                showQuickJumper: true, // 跳转
                showSizeChanger: true, // 显示改变每页数量
                total: res.data.total, // 总数
                pageSizeOptions: ['10', '15', '20', '25'],
                showTotal: total => `共 ${total} 条` // 显示总数
              },
              selectedRowKeys: [],
              data: res.data.list
            }
          })
        }
        // 获取选中设备列表
        queryChooseEquipmentId({
          entinfoId: entinfoId,
          workshopId: workshopId,
          type: '1'
        }).then(res => {
          if (res.code === '0') {
            if (res.data) {
              for (const item in res.data) {
                this.ruleData.forEach(el => {
                  if (el.value === item) {
                    el.selectedRowKeys = res.data[item].map(element => element.equipmentIds)
                  }
                })
              }
            }
          }
          this.pageReady = true
        }).catch(error => {
          console.log(error)
          this.pageReady = true
        })
        this.saveDisabled = !this.ruleData.some(el => {
          return el.data.length > 0
        })
      }).catch(error => {
        console.log(error)
        this.pageReady = true
      })
    },
    // 企业树选中
    treeSelect (selectedKeys, info) {
      if (selectedKeys.length > 0) {
        if (info.selectedNodes[0].data.props.dataRef.children) { // 点击企业
          this.getEquipmentData(selectedKeys[0])
        } else { // 点击生产线
          let entinfoId = ''
          for (let i = 0; i < this.treeData.length; i++) {
            if (this.treeData[i].children) {
              for (let j = 0; j < this.treeData[i].children.length; j++) {
                if (this.treeData[i].children[j].key === selectedKeys[0]) {
                  entinfoId = this.treeData[i].key
                  break
                }
              }
            }
          }
          this.getEquipmentData(entinfoId, selectedKeys[0])
        }
      }
    },
    // 行选中
    rowSelection (item) {
      return {
        selectedRowKeys: item.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          item.selectedRowKeys = selectedRowKeys
        }
      }
    },
    // 设置设备规则
    saveRule () {
      this.saveLoading = true
      this.ruleData.forEach(el => {
        el.loading = true
      })
      saveRule({
        entinfoId: this.equipmentInfo.entinfoId,
        workshopId: this.equipmentInfo.workshopId,
        type: '1',
        hnRuleEquipmentList: this.ruleData.map(el => {
          return {
            equipmentIds: el.selectedRowKeys,
            warning: el.value
          }
        }).filter(el => el)
      }).then(res => {
        this.saveLoading = false
        this.ruleData.forEach(el => {
          el.loading = false
        })
        if (res.code === '0') {
          this.$message.success('设置成功!')
        }
      }).catch(error => {
        console.log(error)
        this.saveLoading = false
        this.saveLoading = false
        this.ruleData.forEach(el => {
          el.loading = false
        })
      })
    },
    // 分页查询设备
    getEquipment (pageNum, pageSize, item) {
      item.loading = true
      this.saveDisabled = true
      queryAllRuleEquipment({
        pageNum: pageNum,
        pageSize: pageSize,
        param: {
          entinfoId: this.equipmentInfo.entinfoId,
          workshopId: this.equipmentInfo.workshopId
        }
      }).then(res => {
        if (res.code === '0') {
          item.data = res.data.list
        }
        item.loading = false
        this.saveDisabled = false
      }).catch(error => {
        console.log(error)
        item.loading = false
        this.saveDisabled = false
      })
    },
    // 表格变动
    tableChange (pagination, item) {
      item.pagination = pagination
      this.getEquipment(item.pagination.current, item.pagination.pageSize, item)
    }
  }
}
</script>
<style lang="scss">
.one-factory-one-policy {
  display: flex;
  height: 100%;
  position: relative;
}
.one-factory-one-policy-source {
  width: 256px;
  min-height: 100%;
  position: relative;
  margin-right: 20px;
  padding: 20px;
  background-color: #fff;
}
.one-factory-one-policy-tree {
  height: calc(100% - 124px);
  overflow-x: hidden;
  overflow-y: auto;
  span {
    max-width: 174px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
.one-factory-one-policy-rule-table {
  flex: 1;
  padding-left: 20px;
  overflow-x: hidden;
  overflow-y: auto;
  padding: 20px;
  background-color: #fff;
}
</style>
